# -*- coding: utf-8 -*-
__author__ = 'sunnychou'
__date__ = '2019/7/22 17:34'

'''
采购付款单处理流程
1. 现将上个月采购付款单导入进来作为基础模板
2. 获取当月的采购订单，获取有交易的供应商信息，将新增供应商加入
3. 计算出对应的统计字段

'''
import datetime
from common.excel_helper import ExcelReader
#from config import *
from common.mssql_helper import g_msql_inst
from common.utils import format_float, create_uuid
from k3_data_report.finance.utils import convert_str_float
import re
from k3_data_report.finance.utils import getLastMonth
from k3_data_report.finance.utils import store_finance_tb_db, check_month_data_exist
#from  k3_data_report.finance.config import EXPORT_TABLE_MAP
from k3_data_report.finance.utils import cal_finance_jine_select
from k3_data_report.finance.config import finace_cal_fields
from k3_data_report.finance.utils import get_exvalue
from k3_data_report.finance.utils import charge_cg_yingfuk_by_jiesuan_type
from common.logger_helper import g_wlogger

def cal_caigou_fkd_process(the_month):
    '''
    :param the_month: 指定月份
    :return:
    '''
    year = the_month.split("-")[0]
    month = the_month.split("-")[1]
    year_first_month = f"{year}-01"  # 年度第一个月
    caigoud_gys_select_sql = finace_cal_fields['caigou_fkd_rp']['caigoud_gys_select'] % the_month
    caigoud_gys_list = g_msql_inst.fetch_all(caigoud_gys_select_sql)
    if caigoud_gys_list == None:
        print("获取供应商信息列表为空！")
        return

    # 获取月订单金额
    caigoud_dingdan_by_month_select_sql = finace_cal_fields['caigou_fkd_rp']['caigoud_dingdan_bymonth'] % the_month
    caigoud_dingdanjine_dict = cal_finance_jine_select(caigoud_dingdan_by_month_select_sql)

    # 获取月入库金额
    waigourk_jine_by_month_select_sql = finace_cal_fields['caigou_fkd_rp']['caigoud_ruku_jine_bymonth'] % the_month
    waigourk_jine_by_month_dict = cal_finance_jine_select(waigourk_jine_by_month_select_sql)

    # 获取本月已付款
    caigoud_yifukuan_bymonth_select_sql = finace_cal_fields['caigou_fkd_rp']['caigoud_yifukuan_bymonth'] % the_month
    caigoud_yifukuan_bymonth_dict = cal_finance_jine_select(caigoud_yifukuan_bymonth_select_sql)

    # 获取已收发票金额
    caigoufp_ysfp_bymonth_select_sql = finace_cal_fields['caigou_fkd_rp']['caigoufp_ysfp_bymonth'] % the_month
    caigoufp_ysfp_bymonth_dict = cal_finance_jine_select(caigoufp_ysfp_bymonth_select_sql)

    # 未收发票
    caigou_weishou_fp_byyear_select_sql = finace_cal_fields['caigou_fkd_rp']['caigou_weishou_fp'] % the_month
    caigou_weishou_fp_dict = cal_finance_jine_select(caigou_weishou_fp_byyear_select_sql)

    # TODO 本月应付款： ---  根据款期不同
    yingfuk_result_dict = charge_cg_yingfuk_by_jiesuan_type(the_month)

    for (gys_code, gys_name, brand,jiesuan_type, paytype) in caigoud_gys_list:

        # 计算订单额（从上月的    采购订单中获取价税合计总和）
        gys_name = gys_name.strip()
        dingdane_by_month = caigoud_dingdanjine_dict.get(gys_name, 0)

        # 计算入库金额
        waigoujine_by_month = waigourk_jine_by_month_dict.get(gys_name, 0)

        # 本月已付款
        caigoud_yifukuan_bymonth = caigoud_yifukuan_bymonth_dict.get(gys_name, 0)

        # 计算已收票
        caigoufp_ysfp_bymonth = caigoufp_ysfp_bymonth_dict.get(gys_name, 0)

        # 未收发票：（实收数量-开票数量）*含税单价
        caigou_weishou_fp = caigou_weishou_fp_dict.get(gys_name, 0)

        # TODO 本月应付款, 问秀丽，预计应付款
        #本月应付款, 需要从销售订单，销售出库，销售发票，收款单-维护
        yingfuk_month_jine = 0
        if jiesuan_type == "款到发货" or jiesuan_type == "款到订货":
            yingfuk_bymonth_dict= yingfuk_result_dict[1]
            yingfuk_month_jine = yingfuk_bymonth_dict.get(gys_name, 0)
        elif jiesuan_type == "货到付款":
            yingfuk_bymonth_dict = yingfuk_result_dict[3]
            yingfuk_month_jine = yingfuk_bymonth_dict.get(gys_name, 0)
        else:
            yingfuk_bymonth_dict = yingfuk_result_dict[2]
            yingfuk_month_jine = yingfuk_bymonth_dict.get(gys_name, 0)

        caigou_fkd_rp_sql = finace_cal_fields['caigou_fkd_rp']['caigou_fkd_insert']
        cur_time = datetime.datetime.now().strftime('%Y-%m-%d')
        if paytype == "人民币":
            id = create_uuid()
            value_tuple = (id, cur_time, gys_code, gys_name, jiesuan_type, brand,
                            dingdane_by_month, waigoujine_by_month,  caigoud_yifukuan_bymonth,
                           yingfuk_month_jine, caigoufp_ysfp_bymonth, caigou_weishou_fp,
                           0, the_month, paytype)
        else:
            id = create_uuid()
            print(f"美元 -- 》  gys_code:{gys_code}, gys_name:{gys_name}, caigoud_yifukuan_bymonth:{caigoud_yifukuan_bymonth}")
            value_tuple = (id, cur_time, gys_code, gys_name, jiesuan_type, brand,
                            dingdane_by_month, waigoujine_by_month,  caigoud_yifukuan_bymonth,
                           yingfuk_month_jine, 0, 0,
                           0, the_month, paytype)
        store_finance_tb_db(caigou_fkd_rp_sql, value_tuple)
        print(f"供应商代码:{gys_code}, 内容:[{value_tuple} 保存数据库")


def cal_caigou_fkd_process_main(the_month):
    try:
        from k3_data_report.business.cgtj_db import Cgtj
        check_sql = "select distinct tjmonth from k3cgfkds where tjmonth='%s'" % the_month
        check_dic = Cgtj.check_cf(check_sql)
        if len(check_dic) > 0:  # 有数据，不需要插入
            g_wlogger.winfo(f"cal_caigou_fkd_process_main already existed with month:{the_month}.")
            return

        cal_caigou_fkd_process(the_month)
        return True
    except Exception as e:
        print(f"cal_caigou_fkd_process_main has error:{e}")
        return False


